import request from '../utls/require'

// 定义公司数据接口
export interface Company {
  id: string | number
  name: string
  legal_person?: string
  registration_number?: string
  industry?: string
  registered_capital?: string
  registration_date?: string
  contact_phone?: string
  contact_email?: string
  [key: string]: any
}

// 创建公司的请求参数接口
export interface CreateCompanyPayload {
  name: string
  legal_person?: string
  registration_number?: string
  industry?: string
  registered_capital?: string
  registration_date?: string
  contact_phone?: string
  contact_email?: string
  [key: string]: any
}

// 定义公司列表响应接口
export interface CompanyListResponse {
  success: boolean
  data: Company[]
  pagination: PaginationMeta
}

export interface DepartmentPayload {
  name: string
  manager: string
  description?: string
}

export interface Department {
  id: number
  name: string
  manager: string
  description?: string
  created_at: string
  user_count?: number
}

export interface PaginationMeta {
  current_page: number
  total_pages: number
  total_count: number
  has_next?: boolean
  has_previous?: boolean
}

/**
 * 获取公司列表
 * @param params 查询参数
 * @returns 公司列表数据
 */
export const fetchCompanies = (params?: {
  page?: number
  page_size?: number
  search?: string
}) => {
  return request.get<any, CompanyListResponse>('/company/companies/', {
    params: {
      page: params?.page || 1,
      page_size: params?.page_size || 50, // 默认获取较多数据，避免分页加载
      search: params?.search || ''
    }
  })
}

/**
 * 获取单个公司详情
 * @param companyId 公司ID
 * @returns 公司详情
 */
export const fetchCompanyDetail = (companyId: string | number) => {
  return request.get(`/company/companies/${companyId}/`)
}

/**
 * 创建新公司
 * @param payload 公司信息
 * @returns 创建的公司数据
 */
export const createCompany = (payload: CreateCompanyPayload) => {
  return request.post<any, { success: boolean; data: Company }>('/company/companies/', payload)
}

export interface DepartmentListResponse {
  success: boolean
  data: Department[]
  pagination: PaginationMeta
}

export interface DepartmentDetailResponse {
  success: boolean
  data: Department & {
    users: Array<{
      id: number
      name: string
      username: string
      phone: string
      role: string
      hire_date: string
    }>
    user_count: number
  }
}

export interface DepartmentStatsResponse {
  success: boolean
  data: {
    total_departments: number
    total_users: number
    departments: Array<Pick<Department, 'id' | 'name' | 'manager'> & { user_count: number }>
  }
}

export const fetchDepartments = (params?: { page?: number; page_size?: number; search?: string }) => {
  return request.get<any, DepartmentListResponse>('/company/departments/', { params })
}

export const createDepartment = (payload: DepartmentPayload) => {
  return request.post<any, DepartmentDetailResponse>('/company/departments/', payload)
}

export const updateDepartment = (departmentId: number, payload: Partial<DepartmentPayload>) => {
  return request.put<any, DepartmentDetailResponse>(`/company/departments/${departmentId}/`, payload)
}

export const deleteDepartment = (departmentId: number) => {
  return request.delete(`/company/departments/${departmentId}/`)
}

export const fetchDepartmentDetail = (departmentId: number) => {
  return request.get<any, DepartmentDetailResponse>(`/company/departments/${departmentId}/`)
}

export const fetchDepartmentStats = () => {
  return request.get<any, DepartmentStatsResponse>('/company/departments/stats/')
}

export interface FinanceRecordPayload {
  date: string
  department: number
  category: number
  amount: number
  description?: string
  source?: 'manual' | 'import'
}

export interface FinanceRecord {
  id: number
  date: string
  department: string | null
  category: string | null
  amount: string
  description: string | null
  source: string
  user_profile: string | null
  created_at: string
}

export interface FinanceRecordListResponse {
  success: boolean
  data: FinanceRecord[]
  pagination: PaginationMeta
}

export const fetchFinanceRecords = (params?: { page?: number; page_size?: number }) => {
  return request.get<any, FinanceRecordListResponse>('/company/finance/records/', { params })
}

export const createFinanceRecord = (payload: FinanceRecordPayload) => {
  return request.post('/company/finance/records/', payload)
}

export interface FinancialReport {
  id: number
  report_type: 'profit' | 'balance' | 'cashflow'
  period: string
  total_income: string
  total_expense: string
  net_profit: string
  generated_at: string
  generated_by: number | null
}

export interface FinancialReportListResponse {
  success: boolean
  data: FinancialReport[]
}

export const fetchFinancialReports = () => {
  return request.get<any, FinancialReportListResponse>('/company/finance/reports/')
}

export const generateFinancialReport = (payload: { report_type?: FinancialReport['report_type']; period: string }) => {
  return request.post('/company/finance/reports/', payload)
}

export const fetchFinancialReportDetail = (reportId: number) => {
  return request.get(`/company/finance/reports/${reportId}/`)
}

export const analyzeFinancialReport = (reportId: number) => {
  return request.post(`/company/finance/reports/${reportId}/analyze/`)
}

export const fetchFinancialAnalysis = (analysisId: number) => {
  return request.get(`/company/finance/analysis/${analysisId}/`)
}

export const exportCompanyData = (params: {
  model: 'finance_record' | 'financial_report' | 'user_profile' | 'company'
  format?: 'csv' | 'xlsx'
  [key: string]: string | number | boolean | undefined
}) => {
  return request.get('/company/export/', {
    params,
    responseType: params.format === 'xlsx' ? 'arraybuffer' : 'blob'
  })
}

